import { post, apiPaths } from '../../utils/request.js'

Page({
  data: {
    taskId: null,
    projectId: null,
    action: 'create', // 'create' 或 'edit'
    task: {
      title: '',
      projectId: null,
      projectName: '',
      description: '',
      priority: '中',
      priorityClass: 'medium',
      assigneeId: null,
      assigneeName: '',
      dueDate: ''
    },
    projectList: [],
    projectIndex: 0,
    priorityList: ['紧急', '高', '中', '低'],
    priorityIndex: 2,
    assigneeList: [],
    assigneeIndex: 0
  },

  onLoad(options) {
    console.log('CreateTask page loaded with options:', options);
    
    if (options.projectId) {
      this.setData({
        projectId: options.projectId
      })
      console.log('Project ID set:', options.projectId);
    }
    
    if (options.taskId) {
      this.setData({
        taskId: options.taskId,
        action: 'edit'
      })
      console.log('Task ID set:', options.taskId);
      // 加载任务详情
      this.loadTaskDetail(options.taskId)
      wx.setNavigationBarTitle({
        title: '编辑任务'
      })
    } else {
      wx.setNavigationBarTitle({
        title: '创建任务'
      })
    }
    
    // 加载项目列表
    this.loadProjects()
    
    // 加载项目成员列表
    this.loadProjectMembers()
  },

  loadProjects() {
    // 调用获取项目列表接口
    post(apiPaths.getProjects).then(res => {
      if (res.code === 200) {
        const projects = res.data || []
        this.setData({
          projectList: projects
        })
        
        // 如果是从项目详情页面跳转过来的，设置默认选中的项目
        if (this.data.projectId) {
          const projectIndex = projects.findIndex(p => p.id == this.data.projectId)
          if (projectIndex >= 0) {
            this.setData({
              projectIndex: projectIndex,
              'task.projectId': this.data.projectId,
              'task.projectName': projects[projectIndex].name
            })
          }
        }
      }
    }).catch(err => {
      console.log('获取项目列表失败:', err)
    })
  },

  loadTaskDetail(taskId) {
    // 调用获取任务详情接口
    post(apiPaths.getTaskDetail, { id: taskId }).then(res => {
      if (res.code === 200) {
        const data = res.data
        const task = {
          id: data.task.id,
          title: data.task.title,
          projectId: data.task.project_id,
          projectName: data.task.project_name,
          description: data.task.description,
          priority: data.task.priority,
          priorityClass: this.getPriorityClass(data.task.priority),
          assigneeId: data.task.assignee_id,
          assigneeName: data.task.assignee_name,
          dueDate: data.task.due_date,
          projectName: data.task.project_name,
          creatorName: data.task.creator_name,
          createdAt: data.task.created_at,
          updatedAt: data.task.updated_at
        }
        
        this.setData({
          task: task
        })
        
        // 设置项目选择
        if (task.projectId) {
          const projectIndex = this.data.projectList.findIndex(p => p.id == task.projectId)
          if (projectIndex >= 0) {
            this.setData({
              projectIndex: projectIndex
            })
          }
        }
      } else {
        wx.showToast({
          title: res.message || '获取任务详情失败',
          icon: 'none'
        })
      }
    }).catch(err => {
      wx.showToast({
        title: err.message || '获取任务详情失败',
        icon: 'none'
      })
    })
  },

  onProjectChange(e) {
    const index = e.detail.value
    const project = this.data.projectList[index]
    
    this.setData({
      projectIndex: index,
      'task.projectId': project.id,
      'task.projectName': project.name
    })
    
    // 重新加载项目成员列表
    this.loadProjectMembers()
  },

  loadProjectMembers() {
    if (!this.data.task.projectId) return
    
    // 调用获取项目成员接口
    post(apiPaths.getProjectMembers, {
      projectId: this.data.task.projectId
    }).then(res => {
      if (res.code === 200) {
        const members = res.data || []
        this.setData({
          assigneeList: members
        })
      }
    }).catch(err => {
      console.log('获取项目成员失败:', err)
    })
  },

  onTitleInput(e) {
    this.setData({
      'task.title': e.detail.value
    })
  },

  onDescriptionInput(e) {
    this.setData({
      'task.description': e.detail.value
    })
  },

  onPriorityChange(e) {
    const index = e.detail.value
    const priority = this.data.priorityList[index]
    const priorityClass = this.getPriorityClass(priority)
    
    this.setData({
      priorityIndex: index,
      'task.priority': priority,
      'task.priorityClass': priorityClass
    })
  },

  onAssigneeChange(e) {
    const index = e.detail.value
    const assignee = this.data.assigneeList[index]
    
    this.setData({
      assigneeIndex: index,
      'task.assigneeId': assignee.id,
      'task.assigneeName': assignee.name
    })
  },

  onDueDateChange(e) {
    this.setData({
      'task.dueDate': e.detail.value
    })
  },

  getPriorityClass(priority) {
    switch (priority) {
      case '紧急':
        return 'urgent'
      case '高':
        return 'high'
      case '中':
        return 'medium'
      case '低':
        return 'low'
      default:
        return 'medium'
    }
  },

  onSaveTask() {
    if (!this.data.task.title) {
      wx.showToast({
        title: '请输入任务标题',
        icon: 'none'
      })
      return
    }
    
    if (!this.data.task.projectId) {
      wx.showToast({
        title: '请选择项目',
        icon: 'none'
      })
      return
    }
    
    const userInfo = wx.getStorageSync('userInfo') || {}
    const userId = userInfo.id
    
    if (!userId) {
      wx.showToast({
        title: '用户信息错误',
        icon: 'none'
      })
      return
    }
    
    if (this.data.action === 'create') {
      // 创建任务
      // 调用创建任务接口
      post(apiPaths.createTask, {
        projectId: this.data.task.projectId,
        title: this.data.task.title,
        description: this.data.task.description,
        priority: this.data.task.priority,
        assigneeId: this.data.task.assigneeId,
        dueDate: this.data.task.dueDate,
        createdById: userId
      }).then(res => {
        if (res.code === 200) {
          wx.showToast({
            title: '任务创建成功',
            icon: 'success'
          })
          
          // 返回上一页
          setTimeout(() => {
            wx.navigateBack()
          }, 1500)
        } else {
          wx.showToast({
            title: res.message || '任务创建失败',
            icon: 'none'
          })
        }
      }).catch(err => {
        wx.showToast({
          title: err.message || '任务创建失败',
          icon: 'none'
        })
      })
    } else {
      // 编辑任务
      if (!this.data.taskId) {
        wx.showToast({
          title: '任务ID不能为空',
          icon: 'none'
        })
        return
      }
      
      // 调用更新任务接口
      post(apiPaths.updateTask, {
        id: this.data.taskId,
        projectId: this.data.task.projectId,
        title: this.data.task.title,
        description: this.data.task.description,
        priority: this.data.task.priority,
        assigneeId: this.data.task.assigneeId,
        dueDate: this.data.task.dueDate
      }).then(res => {
        if (res.code === 200) {
          wx.showToast({
            title: '任务更新成功',
            icon: 'success'
          })
          
          // 返回上一页
          setTimeout(() => {
            wx.navigateBack()
          }, 1500)
        } else {
          wx.showToast({
            title: res.message || '任务更新失败',
            icon: 'none'
          })
        }
      }).catch(err => {
        wx.showToast({
          title: err.message || '任务更新失败',
          icon: 'none'
        })
      })
    }
  },

  onCancel() {
    wx.navigateBack()
  }
})